import { messages, deepFullCopy, queryCurrencyPrecision } from "share/common";
import React from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import { Affix, Button, Table, Row, Col, Popover, Spin, Popconfirm, message, Icon } from 'antd'

import SlideFrame from 'components/slide-frame'
import Condition from 'components/condition'
const { If, Else } = Condition;
import ruleOptions from 'containers/expense-reimbursement-control/expense-standard/reimbursement/rule-options.data'
import NewStandard from 'containers/expense-reimbursement-control/expense-standard/reimbursement/new-standard'
import EditRule from 'containers/expense-reimbursement-control/expense-standard/reimbursement/new-rule'
import EditControl from 'containers/expense-reimbursement-control/expense-standard/reimbursement/edit-control'
import 'styles/expense-reimbursement-control/reimbursement/rule-detail.scss'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import summaryCheckInfoEn from 'images/expense/summary-check-info-en.png'
import errorMessage from 'share/errorMessage'

class RuleDetail extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      basicInfoLoading: false,
      tableLoading: false,
      controlLoading: false,
      infoList: deepFullCopy(ruleOptions),
      infoData: {},
      columns: [
        {title: messages("common.sequence"/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) =>
          index + 1 + this.state.pageSize * this.state.page},
        {dataIndex: 'citys', title: messages('expense-reimbursement-control.key27')/*适用城市*/, width: '30%', render: (value, record) => {
          let showCity = [];
          (value || []).map(item => showCity.push(item.levelName));
          let showValue = `${record.cityAssociateType === 0 ? `(${messages('expense-reimbursement-control.key72')/*不包含*/})` : ''}${showCity.join('、')}`;
          return showCity.length ? (
            <Popover placement="topLeft"
                     overlayStyle={{maxWidth: 500}}
                     content={showValue}>{showValue}</Popover>
          ) : messages('expense-reimbursement-control.key28')/*通用*/
        }},
        {dataIndex: 'userGroups', title: messages('expense-reimbursement-control.key29')/*适用人员*/, width: '30%', render: (value, record) => {
          let showUser = [];
          (value || []).map(item => showUser.push(item.name));
          let showValue = `${record.userAssociateType === 0 ? `(${messages('expense-reimbursement-control.key72')/*不包含*/})` : ''}${showUser.join('、')}`;
          return showUser.length ? (
            <Popover placement="topLeft"
                     overlayStyle={{maxWidth:500}}
                     content={showValue}>{showValue}</Popover>
          ) : messages('expense-reimbursement-control.key28')/*通用*/
        }},
        {dataIndex: 'currencyCode', title: messages('common.currency'/*币种*/), width: '5%'},
        {dataIndex: 'amount', title: messages('common.amount'/*金额*/), width: '10%', render: (value, record) => (
          !value && value !== 0 ? <div className="amount-column">{messages('expense-reimbursement-control.key30')/*不限制*/}</div> :
            this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
        )},
        {dataIndex: 'standardOID', title: messages('common.operation'/*操作*/), width: '20%', render: () => '-'},
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {total: 0},
      slideFrameOptions: {
        content: () => <div/>,
        params: {},
        title: ''
      },
      slideFrameVisible: false,
      controlText: '',
      controlConditions: [],
    }
  }

  componentDidMount() {
    this.getInfo();
    this.getStandard();
    this.getControl()
  }

  //获取规则详情
  getInfo = () => {
    const { params } = this.props;
    this.setState({ basicInfoLoading: true });
    reimburseService.getRuleInfo(params.ruleOID).then(res => {
      this.setState({ infoData: res.data }, () => {
        this.setColumns();
        this.modifyInfoList()
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ basicInfoLoading: false })
    })
  };

  //获取基本标准
  getStandard = () => {
    const { page, pageSize } = this.state;
    let params = { page, size: pageSize };
    this.setState({ tableLoading: true });
    reimburseService.getStandardList(this.props.params.ruleOID, params).then(res => {
      this.setState({
        tableLoading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count'] || 0),
          onChange: this.onChangePager,
          current: page + 1
        }
      },() => {
        this.setColumns()
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ tableLoading: false  })
    })
  };

  //获取管控信息
  getControl = () => {
    this.setState({ controlLoading: true });
    reimburseService.getControlInfo(this.props.params.ruleOID).then(res => {
      this.setState({
        controlLoading: false,
        controlText: res.data.frontShowValue,
        controlConditions: res.data.conditions || []
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ controlLoading: false })
    })
  };

  //设置表格列
  setColumns = () => {
    const { tenantMode } = this.props;
    let { columns, infoData, data } = this.state;
    columns.map(item => {
      if (item.dataIndex === 'standardOID') {
        if (tenantMode || (!tenantMode && infoData.source === 1002)) {
          item.render = (value, record) => (
            <div className="operate-column">
              <a onClick={() => this.handleEditSlideFrame('standard', {standardOID: value, info: record})}>
                {messages('common.edit')/*编辑*/}
              </a>
              <a className="copy" onClick={() => this.handleEditSlideFrame('standard', {info: record})}>
                {messages('common.copy')/*复制*/}
              </a>
              <If value={data.length > 1}>
                <Popconfirm title={messages('common.confirm.delete')/*确定要删除吗？*/} onConfirm={() => this.deleteStandard(value)}>
                  <a className="delete">{messages('common.delete')/*删除*/}</a>
                </Popconfirm>
              </If>
            </div>
          )
        }
      }
    });
    this.setState({ columns })
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getStandard()
      })
    }
  };

  //修改基本信息列表
  modifyInfoList = () => {
    const { language } = this.props;
    let { infoData, infoList } = this.state;
    infoList[0].id !== 'code' && infoList.splice(0, 0, {
      id: 'code',
      label: messages('expense-reimbursement-control.key18')/*规则编码*/,
      type: 'input',
      disabled: true,
      initialValue: infoData.code,
      rules: [{
        required: true
      }]
    });
    infoList.map((item, index) => {
      if (item.id === 'controlType') {
        if (language.code === 'en') {
          item.label = (
            <span> {messages('expense-reimbursement-control.key33')/*控制方式*/}
              <Popover content={<img src={summaryCheckInfoEn} style={{width: 800}}/>}
                       overlayStyle={{maxWidth: 832}}>
                <Icon type="info-circle" className='default-color-font' style={{cursor: 'pointer', marginLeft: 5}} />
              </Popover>
            </span>
          )
        }
        if (infoData.controlType === 'SUMMARY') { //控制方式: 汇总校验
          let standardItem = {
            id: 'participantsEnable',
            label: messages('expense-reimbursement-control.key23')/*费用参与人标准*/,
            type: 'switch',
            initialValue: infoData.participantsEnable,
            rules: []
          };
          let notTogetherItem = {
            id: 'nonParticipants',
            label: messages('expense-reimbursement-control.key24')/*不参与同住管控的人员*/,
            type: 'chooser',
            placeholder: messages('expense-reimbursement-control.key25')/*不填写则默认全部参与同住管控*/,
            chooserType: 'user_group',
            valueKey: 'id',
            labelKey: 'name',
            listExtraParams: {},
            initialValue: infoData.nonParticipants,
            rules: []
          };
          infoList[index + 1].id !== 'participantsEnable' && infoList.splice(index + 1, 0, standardItem);
          infoData.participantsEnable && infoList[index + 2].id !== 'nonParticipants' && infoList.splice(index + 2, 0, notTogetherItem)
        } else {
          infoList[index + 2].id === 'nonParticipants' && infoList.splice(index + 2, 1);
          infoList[index + 1].id === 'participantsEnable' && infoList.splice(index + 1, 1);
        }
      }
    });
    this.setState({ basicInfoLoading: false, infoList })
  };

  filterInfo = (id) => {
    const { infoData } = this.state;
    switch (id) {
      case 'expenseTypes':
      case 'userGroups':
      case 'forms':
      case 'companys':
      case 'nonParticipants':
        let showValue = [];
        infoData[id] && infoData[id].map(valueItem => {
          showValue.push(valueItem.name || valueItem.formName)
        });
        return (~['companys', 'userGroups', 'forms'].indexOf(id) && !showValue.length) ? messages('expense-reimbursement-control.key28')/*通用*/ : showValue.join('、');
      case 'controlType':
        return (
          infoData[id] === 'DAY' ? messages('expense-reimbursement-control.key34')/*每天*/ :
            (infoData[id] === 'MONTH' ? messages('expense-reimbursement-control.key35')/*每月*/ :
              (infoData[id] === 'QUARTER' ? messages('expense-reimbursement-control.key36')/*每季度*/ : messages('expense-reimbursement-control.key37')/*汇总校验*/))
        );
      case 'crossCompanyStandard':
        return infoData[id] === 'OWNER' ? messages('expense-reimbursement-control.key44')/*费用归属人*/ : messages('expense-reimbursement-control.key45')/*单据所选公司下的标准*/;
      case 'controlLevel':
        return infoData[id] === 'WARN' ? messages('expense-reimbursement-control.key46')/*警告*/ : messages('expense-reimbursement-control.key47')/*禁止*/;
      case 'participantsEnable':
        return infoData[id] ? (infoData.participantsMode === 'HIGH' ? messages('expense-reimbursement-control.key19')/*就高*/ : messages('expense-reimbursement-control.key21')/*和值*/) : messages("common.status.disable");
      case 'status':
      case 'complianceCheck':
        return infoData[id] ? messages("common.status.enable") : messages("common.status.disable");
      default:
        return infoData[id]
    }
  };

  //侧滑框数据初始化
  handleEditSlideFrame = (type, extraParams = {}) => {
    const { params } = this.props;
    let { infoData, slideFrameOptions, controlConditions } = this.state;
    switch(type) {
      case 'rule':
        slideFrameOptions = {
          content: EditRule,
          params: {
            info: infoData,
            setOfBooksId: params.setOfBooksId
          },
          title: messages('common.baseInfo')/*基本信息*/
        };
        break;
      case 'standard':
        slideFrameOptions = {
          content: NewStandard,
          params: {
            ruleOID: params.ruleOID,
            standardOID: extraParams.standardOID,
            info: extraParams.info || {}
          },
          title: messages('expense-reimbursement-control.key48')/*编辑标准*/
        };
        break;
      case 'control':
        slideFrameOptions = {
          content: EditControl,
          params: {
            ruleOID: params.ruleOID,
            conditions: controlConditions
          },
          title: messages('expense-reimbursement-control.key49')/*管控信息*/
        };
        break;
    }
    this.setState({ slideFrameOptions }, () => {
      this.setState({ slideFrameVisible: true })
    })
  };

  //删除基本标准
  deleteStandard = (standardOID) => {
    this.setState({ tableLoading: true });
    reimburseService.deleteStandard(standardOID).then(() => {
      message.success(messages('common.delete.success', {name: ""})/*删除成功*/);
      this.getStandard()
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ tableLoading: false })
    })
  };

  afterSlideFrameClose = (type) => {
    this.setState({
      slideFrameVisible: false,
      slideFrameOptions: {
        content: () => <div/>,
        params: {},
        title: ''
      }
    });
    if (type === 'rule') {
      this.getInfo()
    }
    if (type === 'standard') {
      this.getStandard()
    }
    if (type === 'control') {
      this.getControl()
    }
    if (type === 'ruleAndControl') {
      this.getInfo();
      this.getControl()
    }
  };

  //返回
  onCancel = () => {
    let listUrl = menuRoute.getRouteItem('expense-standard').url;
    this.context.router.push(listUrl)
  };

  render() {
    const { tenantMode } = this.props;
    const { basicInfoLoading, tableLoading, controlLoading, infoList, columns, data, slideFrameVisible, slideFrameOptions,
      pagination, controlText, infoData } = this.state;
    return (
      <div className="rule-detail background-transparent">
        <div className="block-container">
          <Spin spinning={basicInfoLoading}>
            <div className="tab-container">
              <h3 className="sub-header-title"> {messages('common.baseInfo')/*基本信息*/}
                <If value={tenantMode || (!tenantMode && infoData.source === 1002)}>
                  <a className="edit" onClick={() => this.handleEditSlideFrame('rule')}>
                    {messages('common.edit')/*编辑*/}
                  </a>
                </If>
              </h3>
              <Row type="flex">
                {infoList.map((item, index) => (
                  <Col span={8} key={index} className="field-col">
                    <div className="field-name">{item.label}</div>
                    <div className="field-content">
                      <Condition>
                        <If value={this.filterInfo(item.id)}>
                          <Popover content={this.filterInfo(item.id)} placement="topLeft" overlayStyle={{maxWidth:500}}>
                            {this.filterInfo(item.id)}
                          </Popover>
                        </If>
                        <Else>-</Else>
                      </Condition>
                    </div>
                  </Col>
                ))}
              </Row>
            </div>
          </Spin>
        </div>
        <div className="block-container">
          <div className="tab-container">
            <h3 className="sub-header-title">{messages('expense-reimbursement-control.key16')/*基本标准*/}</h3>
            <div className="table-header">
              <div className="table-header-buttons">
                <If value={tenantMode || (!tenantMode && infoData.source === 1002)}>
                  <Button type="primary" onClick={() => this.handleEditSlideFrame('standard')}> {messages('expense-reimbursement-control.key50')/*新增*/}
                  </Button>
                </If>
              </div>
            </div>
            <Table rowKey="standardOID"
                   columns={columns}
                   dataSource={data}
                   loading={tableLoading}
                   pagination={pagination}
                   size="middle"
                   bordered
            />
          </div>
        </div>
        <div className="block-container">
          <div className="tab-container">
            <h3 className="sub-header-title"> {messages('expense-reimbursement-control.key49')/*管控信息*/}
              <If value={(tenantMode || (!tenantMode && infoData.source === 1002)) && infoData.controlType === 'SUMMARY'}>
                <a className="edit" onClick={() => this.handleEditSlideFrame('control')}>
                  {messages('common.edit')/*编辑*/}
                </a>
              </If>
            </h3>
            <div className="control-info">
              <Spin spinning={controlLoading}>{controlText}</Spin>
            </div>
          </div>
        </div>
        <Affix offsetBottom={0} className='bottom-bar'>
          <Button onClick={this.onCancel}>{messages("common.back")/*返回*/}</Button>
        </Affix>

        <SlideFrame show={slideFrameVisible}
                    content={slideFrameOptions.content}
                    params={slideFrameOptions.params}
                    title={slideFrameOptions.title}
                    onClose={() => this.setState({slideFrameVisible: false})}
                    afterClose={this.afterSlideFrameClose}
        />
      </div>
    )
  }
}

RuleDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(RuleDetail)
